<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { useGetGoodTypes } from '@/services/pages/good/type'
  import { useGetGoods } from '@/services/pages/order/create'
  import { computed, onBeforeUnmount, ref } from 'vue'
  import { getBrowserHeightSize } from '@/utils/tools'
  import { onMounted } from 'vue'
  import defaultImg from '@/assets/image/default.png'
  import _ from 'lodash'
  import useGoods from '../useGoods'
  import { TableInstance } from 'element-plus'
  import { nextTick } from 'vue'
  import { useGetAllGoodTypeOptions } from '@/services/pages/good/useType'

  const { getGoodTypesParam, getGoodTypesLoading, getGoodTypes } = useGetGoodTypes()
  const {
    options: goodTypeOptionList,
    getOptionsLoading: getGoodTypeOptionListLoading,
    getOptions: getGoodTypeOptionList,
  } = useGetAllGoodTypeOptions()
  const { goods, goodsTotal, getGoodsParam, getGoodsLoading, getGoods } = useGetGoods()
  const { goods: defaultSelectedGoodList } = useGoods()

  defineOptions({
    name: 'GoodsSelectGoodOrderCreate',
  })

  const paginationInstance = ref<InstanceType<typeof Pagination> | null>(null)
  const selectedGoodList = ref<Array<OrderGood>>([])
  const tableInstance = ref<TableInstance | null>(null)
  const unSelectedGoods = ref<Array<OrderGood>>([])

  // 设备分类列表
  const goodTypeList = computed<
    Array<{ id: string; name: string; childData: Array<GoodTypeOptions> }>
  >(() => {
    return [
      {
        id: '',
        name: '全部',
        childData: [],
      },
      ...goodTypeOptionList.value,
    ]
  })

  // 设备分类树形选择器配置
  const goodTypeTreeProps = {
    children: 'childData',
    label: 'name',
  }

  // 选中的设备分类的id
  const selectingGoodTypeId = ref('')

  // const handleChangeGoodTypesPage = (page: number) => {
  //   getGoodTypesParam.value.page = page
  //   getGoodTypes()
  // }

  const setGoodTypePagiantionLimit = () => {
    const browserHeightSize = getBrowserHeightSize()
    if (browserHeightSize === 'lg') {
      getGoodTypesParam.value.limit = 20
      getGoodTypes()
    }

    if (browserHeightSize === 'md') {
      getGoodTypesParam.value.limit = 19
      getGoodTypes()
    }

    if (browserHeightSize === 'sm') {
      getGoodTypesParam.value.limit = 14
      getGoodTypes()
    }

    if (browserHeightSize === 'xs') {
      getGoodTypesParam.value.limit = 12
      getGoodTypes()
    }
  }

  const getList = async () => {
    if (paginationInstance.value && tableInstance.value) {
      tableInstance.value.clearSelection()
      getGoodsParam.value.limit = paginationInstance.value.size
      getGoodsParam.value.page = paginationInstance.value.current
      await getGoods()
      nextTick(() => {
        goods.value.forEach((good) => {
          const selectedGood = defaultSelectedGoodList.value
            .filter((item) => item.type === 3)
            .find(
              (_good) =>
                _good.goodId === good.id &&
                _good.goodSpecId === good.specId &&
                _good.goodsSpecCode === good.code,
            )
          if (selectedGood && tableInstance.value) {
            tableInstance.value.toggleRowSelection(good, true)
          }
        })
      })
    }
  }

  /**
   * 商品分类点击时触发
   * @param {GoodTypeOptions} goodType - 设备分类对象
   */
  const handleGoodTypeClick = (goodType: GoodTypeOptions) => {
    getGoodsParam.value.typeId = ''
    getGoodsParam.value.typeTwoId = ''
    getGoodsParam.value.typeThreeId = ''

    if (goodType.level === 1) {
      getGoodsParam.value.typeId = goodType.id
    }

    if (goodType.level === 2) {
      getGoodsParam.value.typeTwoId = goodType.id
    }

    if (goodType.level === 3) {
      getGoodsParam.value.typeThreeId = goodType.id
    }
    selectingGoodTypeId.value = goodType.id
    getList()
  }

  const handleSelectGood = (_selectedGoodList: Array<OrderGood>, row: OrderGood) => {
    selectedGoodList.value = _selectedGoodList
    const isExist = _selectedGoodList.some(
      (item) => item.id === row.id && item.specId === row.specId && item.code === row.code,
    )
    if (defaultSelectedGoodList.value.filter((item) => item.type === 3).length > 0 && !isExist) {
      unSelectedGoods.value.push(row)
    }
  }

  const handleSelectAllGood = (_selectedGoodList: Array<OrderGood>) => {
    selectedGoodList.value = _selectedGoodList
    unSelectedGoods.value = []
  }

  onMounted(() => {
    setGoodTypePagiantionLimit()
    window.addEventListener('resize', setGoodTypePagiantionLimit)
  })

  onBeforeUnmount(() => {
    unSelectedGoods.value = []
    window.removeEventListener('resize', setGoodTypePagiantionLimit)
  })

  defineExpose({
    getGoodTypes,
    getGoodTypeOptionList,
    getGoodList: (brandId = '', factoryId = '', keyword = '') => {
      getGoodsParam.value.brandId = brandId
      getGoodsParam.value.keyword = keyword
      // getGoodsParam.value.factoryId = factoryId
      getList()
    },
    getSelectedGoodList: () => {
      return _.cloneDeep(selectedGoodList.value)
    },
    getUnSelectedGoods: () => {
      return _.cloneDeep(unSelectedGoods.value)
    },
  })
</script>

<template>
  <div
    v-loading="getGoodTypesLoading || getGoodsLoading || getGoodTypeOptionListLoading"
    class="goods-select-good-order-create"
  >
    <div class="sidebar">
      <div class="title"> 设备分类 </div>
      <div class="type-list-wrapper">
        <!-- <div
          :class="{
            all: true,
            'type-item': true,
            'type-item-active': getGoodsParam.typeId === '',
          }"
          @click="handleGoodTypeClick('')"
          >全部</div
        >
        <div class="type-list">
          <div
            v-for="(type, typeIndex) in goodTypes"
            :key="typeIndex"
            :class="{
              'type-item': true,
              'type-item-active': getGoodsParam.typeId === type.id,
            }"
            @click="handleGoodTypeClick(type.id)"
          >
            <h-tooltip-text :max-width="176" :height="28" :text="type.name"></h-tooltip-text>
          </div>
        </div> -->
        <el-tree :accordion="true" :data="goodTypeList" :props="goodTypeTreeProps" node-key="id">
          <template #default="{ data }">
            <div
              :class="{
                'type-item': true,
                'type-item-active': selectingGoodTypeId === data.id,
              }"
              @click="handleGoodTypeClick(data)"
            >
              <h-tooltip-text :text="data.name" :height="32" :max-width="120"></h-tooltip-text>
            </div>
          </template>
        </el-tree>
      </div>
      <!-- <div class="type-pagination">
        <el-pagination
          hide-on-single-page
          size="small"
          :pager-count="5"
          :current-page="getGoodTypesParam.page"
          :page-size="getGoodTypesParam.limit"
          :total="goodTypeTotal"
          layout="prev, pager, next"
          @current-change="handleChangeGoodTypesPage"
        />
      </div> -->
    </div>
    <div class="table-wrapper">
      <div class="table">
        <el-table
          ref="tableInstance"
          :border="true"
          :data="goods"
          height="100%"
          @select="handleSelectGood"
          @select-all="handleSelectAllGood"
        >
          <el-table-column
            type="selection"
            width="50"
            fixed="left"
            :align="'center'"
          ></el-table-column>
          <el-table-column
            type="index"
            width="50"
            fixed="left"
            :align="'center'"
            label="序号"
          ></el-table-column>
          <el-table-column show-overflow-tooltip prop="code" label="设备编号"></el-table-column>
          <el-table-column show-overflow-tooltip prop="brand" label="品牌"></el-table-column>
          <el-table-column show-overflow-tooltip prop="name" label="名称"></el-table-column>
          <el-table-column show-overflow-tooltip prop="model" label="型号"></el-table-column>
          <el-table-column show-overflow-tooltip prop="specName" label="规格"></el-table-column>
          <el-table-column show-overflow-tooltip prop="contractNo" label="合同号"></el-table-column>
          <el-table-column label="图片">
            <template #default="{ row }">
              <div v-if="row.image" class="pic">
                <h-image
                  :width="40"
                  :height="25"
                  :src="row.image || defaultImg"
                  :padding="2"
                  :show-del-btn="false"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="warrantyDay"
            label="质保时间（天）"
            width="110"
          ></el-table-column>
        </el-table>
      </div>
      <div class="goods-pagination">
        <Pagination
          ref="paginationInstance"
          :list_total="goodsTotal"
          @size-change="getList"
          @current-change="getList"
        ></Pagination>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
  .goods-select-good-order-create {
    display: flex;
    column-gap: 12px;
    height: 99%;

    .sidebar {
      width: 250px;
      height: calc(100% - 40px);
      box-sizing: border-box;
      padding: 0 12px 12px 12px;
      border: 1px solid #ebeef5;
      display: flex;
      flex-direction: column;

      .title {
        height: 40px;
        line-height: 40px;
        border-bottom: 1px solid #ebeef5;
        box-sizing: border-box;
        padding-left: 24px;
        font-size: 14px;
        margin-bottom: 5px;
      }

      .type-list-wrapper {
        display: flex;
        flex-direction: column;
        row-gap: 5px;
        flex: 1;
        height: 0;
        overflow-y: auto;

        :deep(.el-tree) {
          .el-tree-node__content {
            height: 32px;
            border-radius: 2px;

            .custom-tree-node {
              display: flex;
              justify-content: space-between;
              align-items: center;
              width: 100%;
              box-sizing: border-box;
              height: 100%;
            }
          }

          .el-tree-node__content:has(.is_disable) {
            cursor: not-allowed;
          }

          .el-tree-node__content:has(.type-item-active) {
            color: #007cff !important;
            background-color: rgba(0, 123, 255, 0.137254902) !important;

            .el-tree-node__expand-icon {
              color: #007cff !important;
            }
          }
        }

        // .type-item {
        //   height: 28px;
        //   box-sizing: border-box;
        //   line-height: 28px;
        //   cursor: pointer;
        // }

        // .type-item-active {
        // background-color: rgba(0, 123, 255, 0.137254902) !important;
        // color: #007cff;
        // }
      }
    }

    .table-wrapper {
      flex: 1;
      width: 0;
      display: flex;
      flex-direction: column;
      row-gap: 12px;

      .table {
        max-height: calc(100% - 40px);
      }
    }

    .goods-pagination {
      display: flex;
      justify-content: flex-end;
    }
  }
</style>
